package cn.funnymap.lgis.params.validation;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * MultipartFile文件扩展名校验器
 *
 * @author jiaoxn
 */
@ConditionalOnClass(Constraint.class)
public class MultipartFileExtensionValidator implements ConstraintValidator<MultipartFileExtensionAnno, Object> {
    private final Set<String> supportFileTypes = new HashSet<>();

    @Override
    public void initialize(MultipartFileExtensionAnno constraintAnnotation) {
        String[] vals = constraintAnnotation.value();
        for (String val : vals) {
            this.supportFileTypes.add(val.toLowerCase());
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        // 如果文件为空，默认校验通过
        if (value == null) {
            return true;
        }

        // 如果是List<MultipartFile>类型
        if (value instanceof List) {
            for (Object item : (List<?>) value) {
                if (item instanceof MultipartFile) {
                    boolean temp = this.validateMultipartFileExtension((MultipartFile) item);

                    if (!temp) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            return true;
        } else {
            if (value instanceof MultipartFile) {
                return this.validateMultipartFileExtension((MultipartFile) value);
            }
        }

        return false;
    }
    private boolean validateMultipartFileExtension(MultipartFile file) {
        String fileName = file.getOriginalFilename();

        // 如果无法获取文件名，则表示校验失败
        if (fileName == null) {
            return false;
        }

        String fileExtension = this.getFileExtension(fileName);
        return this.supportFileTypes.contains(fileExtension.toLowerCase());
    }
    private String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            // 如果没有找到点号，返回空字符串
            return "";
        }

        // 获取文件后缀名并转换为小写
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }
}
